<?php

class Wants_model extends CI_Model {

	function __construct() {
		parent::__construct();
	}
	
	function insertwant($cat, $desc, $fb_id)
	{
		$data = array(
			'category_id' => $cat,
			'fb_id' => $fb_id,
			'description' => $desc,
		);
		
		$this->db->set('date_created', 'NOW()',false);
		$this->db->set($data);
		$this->db->insert('wants', $data);
	}
	
	function get_want($want_id)
	{
		$sql = 'SELECT * FROM wants WHERE want_id = ?';
		$query = $this->db->query($sql, $want_id);
		if($query->num_rows() > 0){
			$data = $query->row_array();	
		}
		return $data;
	}
	
	function get_related_wants($fb_id, $cat)
	{
		$sql = 'SELECT * FROM offer WHERE fb_id = ? AND category_id = ? ORDER BY date_created DESC';
		
		$query = $this->db->query($sql, array($fb_id, $cat));
		
		$data = array();
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $row)
			{
				$data[] = $row;
			}
		}
		
		return $data;
	}
	
	function delete($want_id)
	{
		$this->db->delete('wants', array('want_id'=>$want_id));
	}
	
	function search($fb_id='', $criteria='')
	{
		$sql = 'SELECT * FROM wants';
		$flag = 0;
		if ($criteria)
		{
			if (array_key_exists('category', $criteria))
			{
				$cat = $criteria['category'];
				if ($cat != 0)
				{
					$sql .= ' WHERE category_id = '.$cat;
					$flag = 1;
				}
			}
			if (array_key_exists('search', $criteria))
			{
				$search = $criteria['search'];
				if ($search != '')
				{
					if ($flag == 0)
					{
						$sql .= " WHERE (LOWER(description) LIKE LOWER('%".$this->db->escape_like_str($criteria['search'])."%'))";
						$flag = 1;
					}
					else
						$sql .= " AND (LOWER(description) LIKE LOWER('%".$this->db->escape_like_str($criteria['search'])."%'))";
					
				}
			}
			if (array_key_exists('filter', $criteria))
			{
				$filter = $criteria['filter'];
				if ($filter == 'mine')
				{
					if ($flag == 0)
					{
						$sql .= ' WHERE fb_id = '.$fb_id;
						$flag = 1;
					}
					else
						$sql .= ' AND fb_id = '.$fb_id;
				}
				else if ($filter == 'everyoneelse')
				{
					if ($flag == 0)
					{
						$sql .= ' WHERE fb_id <> '.$fb_id;
						$flag = 1;
					}
					else
						$sql .= ' AND fb_id <> '.$fb_id;
				}
			}
		}
		
		$sql .= ' ORDER BY date_created DESC';
		$query = $this->db->query($sql);
		
		$data = array();
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $row)
			{
				$data[] = $row;
			}
		}
		
		return $data;
		
	}
}